package online.xuping.center.user.service.impl;

import com.github.artbits.quickio.api.DB;
import com.github.artbits.quickio.core.QuickIO;
import online.xuping.center.user.UserErrorCodeEnum;
import online.xuping.center.user.domain.UserDomain;
import online.xuping.center.user.domain.UserEmailDomain;
import online.xuping.center.user.domain.UserPhoneDomain;
import online.xuping.center.user.service.IUserService;
import online.xuping.common.IdUtils;
import online.xuping.common.PSWUtil;

public class UserServiceImpl implements IUserService {

    private    DB db;

    public UserServiceImpl(String dbName){
        this.db = QuickIO.usingDB(dbName);
    }


    @Override
    public UserDomain newUser(String userName) {

        return newUser(userName,userName);
    }

    @Override
    public UserDomain newUser(String userName, String psw) {
        if (psw == null) {
            throw UserErrorCodeEnum.USER_ADD_PSW_ERROR.exception();
        }
        UserDomain userDomain = new UserDomain();
        userDomain.setName(userName);
        userDomain.setUid(IdUtils.newId());
        userDomain.setPsw(PSWUtil.mPsw(psw));
        try {
            db.collection(UserDomain.class).save(userDomain);
        } catch (Exception e) {
            throw UserErrorCodeEnum.USER_ADD_ERROR.exception();
        }
        return userDomain;
    }

    @Override
    public UserDomain findUser(String userName) {
      return   db.collection(UserDomain.class).findWithIndex(options -> options.index("name", userName));
    }

    @Override
    public UserDomain login(String userName, String psw) {
        UserDomain userDomain = findUser(userName);
        if(PSWUtil.checkPsw(psw,userDomain.getPsw())){
            return userDomain;
        }else {
            throw UserErrorCodeEnum.USER_LOGIN_ERROR.exception();
        }
    }

    @Override
    public UserEmailDomain addUserEmail(String email, String uid) {
        UserEmailDomain userEmailDomain = new UserEmailDomain();
        userEmailDomain.setEmail(email);
        userEmailDomain.setUid(uid);

        try {
            db.collection(UserEmailDomain.class).save(userEmailDomain);
        } catch (Exception e) {
            throw UserErrorCodeEnum.USER_ADD_EMAIL_ERROR.exception();
        }
        return userEmailDomain;
    }

    @Override
    public UserPhoneDomain addUserPhone(String phone, String uid) {
        UserPhoneDomain userPhoneDomain = new UserPhoneDomain();
        userPhoneDomain.setPhone(phone);
        userPhoneDomain.setUid(uid);

        try {
            db.collection(UserPhoneDomain.class).save(userPhoneDomain);
        } catch (Exception e) {
            throw UserErrorCodeEnum.USER_ADD_PHONE_ERROR.exception();
        }
        return userPhoneDomain;
    }
}
